package com.rzjm.api.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.util.OssUtil;
import com.rzjm.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  调查问卷相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/events")//url:模块/资源/{}/细分
public class EventsController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private SurveyService surveyService;
    @Resource
    private EventsTypeService eventsTypeService;
    @Resource
    private EventsSectionService eventsSectionService;
    @Resource
    private EventsRecordService eventsRecordService;
    @Resource
    private EventsRecordImgService eventsRecordImgService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ShopService shopService;
    @Resource
    private DepartmentService departmentService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    /**
     *  事件列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/type/list")
    public JSONObject typList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "type/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int parent_id = jsonRequest.containsKey("parent_id") ? jsonRequest.getInt("parent_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            Shop shop = shopService.findById(user.getShopId());
            if(shop.getState() == 0){
                System.out.println(shop.getShopName() + " 企业已被禁用");
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"企业已被禁用"),true,true);
            }

            QueryWrapper<EventsType> qw = new QueryWrapper<>();
            qw.eq("parent_id",0);
            qw.eq("state",1);
            List<EventsType> eventsTypes = eventsTypeService.list(qw);


            QueryWrapper<EventsType> qwChild = new QueryWrapper<>();
            if(parent_id == 0){
                qwChild.eq("parent_id",eventsTypes.get(0).getId());
            }else{
                qwChild.eq("parent_id",parent_id);
            }
            qwChild.eq("state",1);
            List<EventsType> eventsTypeChilds = eventsTypeService.list(qwChild);

            Map<String,Object> map = new HashMap<>();
            map.put("types",eventsTypes);
            map.put("typeChilds",eventsTypeChilds);


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",eventsTypes.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  事件列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/section/list")
    public JSONObject sectionList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "section/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int type_child_id = jsonRequest.containsKey("type_child_id") ? jsonRequest.getInt("type_child_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            QueryWrapper<EventsSection> qw = new QueryWrapper<>();
            qw.eq("type_child_id",type_child_id);
            qw.eq("state",1);
            List<EventsSection> eventsSections = eventsSectionService.list(qw);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",eventsSections.size(),eventsSections),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  事件列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/section/detail")
    public JSONObject sectionDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "section/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int section_id = jsonRequest.containsKey("section_id") ? jsonRequest.getInt("section_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            EventsSection eventsSection = eventsSectionService.findById(section_id);
            Map<String,Object> map = new HashMap<>();
            map.put("section",eventsSection);



            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  事件列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/section/addRecord")
    public JSONObject sectionAddRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "section/addRecord 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int section_id = jsonRequest.containsKey("section_id") ? jsonRequest.getInt("section_id") : 0;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.getSysUserByUser(user);
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"没有权限"),true,true);
            }

            if(sysUser.getShopId() == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请先绑定企业"),true,true);
            }

            int ret = eventsRecordService.addRecord(sysUser,user_id,section_id,content);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"上报成功",ret),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"上报失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  我的上报事件列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/myRecord/list")
    public JSONObject recordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "myRecord/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
//            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            List<EventsRecord> records = eventsRecordService.myList(user_id,pageIndex,pageSize);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",records.size(),records),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  我所属部门事件列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/departRecord/list")
    public JSONObject departRecordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "departRecord/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.getSysUserByUser(user);
            if(sysUser == null || sysUser.getDeptId() == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未配置部门"),true,true);
            }
            List<EventsRecord> records = eventsRecordService.myDepartList(sysUser,user_id,state,pageIndex,pageSize);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",records.size(),records),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /** 巡检记录的图片上传
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/uploadImg",method = {RequestMethod.POST, RequestMethod.GET},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject uploadImg(@RequestParam("record_id") int record_id,@RequestParam("user_id") int user_id,@RequestParam("img_type") int img_type, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            EventsRecord record = eventsRecordService.getById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "记录不存在"), true, true);
            }
            System.out.println("record_id==" + record_id);

            SysUser sysUser = new SysUser();
            User user = userService.findById(user_id);
            if(user!=null){
                sysUser = sysUserService.getSysUserByUser(user);
            }

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_EVENT_RECORD_PHOTOS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                        EventsRecordImg img = new EventsRecordImg();
                                        img.setRecordId(record_id);
                                        img.setImgUrl(img_key);
                                        img.setImgType(img_type);
                                        img.setUserId(user_id);
                                        img.setSysUserId(sysUser.getUserId());
                                        eventsRecordImgService.save(img);
                                    }
                                } catch (IOException e) {
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

}
